<template>
  <div class="progress-bar" @click="onClick">
    <div class="bar-inner">
      <!--黄色进度条-->
      <div class="progress" ref="progress" :style="progressStyle"></div>
      <div
        class="progress-btn-wrapper"
        :style="btnStyle"
        @touchstart.prevent="onTouchStart"
        @touchmove.prevent="onTouchMove"
        @touchend.prevent="onTouchEnd"
      ></div>
    </div>
  </div>
</template>

<script>
/**
 * 1、支持拖动
 * 2、支持点击
 */
const progressBtnWidth = 16
export default {
  name: 'progress-bar',
  props: {
    progress: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      offset: 0
    }
  },
  created () {
    this.touch = {}
    this.barWidth = 0
  },
  watch: {
    progress (newProgress) {
      this.barWidth = this.$el.clientWidth - progressBtnWidth
      this.offset = this.barWidth * newProgress
    }
  },
  computed: {
    progressStyle () {
      return `width:${this.offset}px`
    },
    btnStyle () {
      return `transform:translate(${this.offset}px, -50%)`
    }
  },
  methods: {
    onTouchStart (e) {
      // 初始横坐标
      this.touch.x1 = e.touches[0].clientX
      this.touch.beginWidth = this.$refs.progress.clientWidth
    },
    onTouchMove (e) {
      const delta = e.touches[0].clientX - this.touch.x1
      const tempWidth = this.touch.beginWidth + delta
      // progress限制在 0-1
      const progress = Math.min(1, Math.max(0, tempWidth / this.barWidth))
      this.offset = progress * this.barWidth
      this.$emit('progress-changing', progress)
    },
    onTouchEnd () {
      const progress = this.$refs.progress.clientWidth / this.barWidth
      this.$emit('progress-changed', progress)
    },
    onClick (e) {
      const react = this.$el.getBoundingClientRect()
      const offsetLeft = e.pageX - react.left
      const progress = Math.min(1, Math.max(0, (offsetLeft / this.barWidth)))
      this.$emit('progress-changed', progress)
    }
  }
}
</script>

<style lang="scss" scoped>
.progress-bar {
  height: 30px;
  .bar-inner {
    position: relative;
    left: 0;
    top: 50%;
    height: 4px;
    background-color: rgba(0, 0, 0, 0.3);
    .progress {
      position: absolute;
      height: 100%;
      background-color: $color-theme;
    }
    .progress-btn-wrapper {
      position: absolute;
      left: 0;
      top: 0;
      transform: translate(-50%, -50%);
      width: 16px;
      height: 16px;
      border-radius: 50%;
      border: 3px solid $color-text;
      box-sizing: border-box;
      background-color: $color-theme;
    }
  }
}
</style>
